package club.kingyin.kyblogprouser.controller;

import club.kingyin.commons.constant.MailHtml;
import club.kingyin.commons.entity.user.User;
import club.kingyin.commons.enums.BlogEnum;
import club.kingyin.commons.mail.MailMessage;
import club.kingyin.commons.response.Result;
import club.kingyin.commons.utils.RandomUtils;
import club.kingyin.kyblogprouser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("mail")
public class EmailController {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserService userService;

    @PostMapping
    public Result sendMail(@RequestBody MailMessage data) {
        return sendMessage(data)?Result.infoN("发送成功"):Result.failN("发送失败");

    }

    @PostMapping("/code")
    public Result sendCode(@RequestBody User user) {
        try {
            String username = user.getUsername();
            User current;
            String subject = "邮箱验证码";
            if ((current = userService.selectByUsername(username)) == null) {
                if (user.getId() != null && user.getId() == 0) {
                    user.setStatus(BlogEnum.MAIL);
                    user.setTitled(0L);
                    subject = "注册验证码";
                    boolean mail = sendMessageHtmlEmpty(sentCode(username, subject));
                    if (mail) {
                        current = userService.insert(user);
                    }
                    return !mail?Result.failR("验证码发送失败，请检查邮箱是否正确"):current==null?Result.failR("验证异常请重新发送验证码"):Result.infoN("验证码发送成功");
                }
            }
            MailMessage msg = sentCode(current.getUsername(), subject);
            return sendMessageHtmlEmpty(msg)?Result.infoN("验证码发送成功"):Result.failN("验证码发送失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.failN("验证码发送失败，请检查邮箱是否正确");
    }

    private MailMessage sentCode(String username, String subject) {
        int code = RandomUtils.createCode();
        redisTemplate.opsForValue().set(username+".code", String.valueOf(code), 6, TimeUnit.MINUTES);
        MailMessage msg = new MailMessage();
        msg.setSubject(subject);
        msg.setContext(MailHtml.codeHtml(code));
        msg.setUsernames(username);
        return msg;
    }

    public boolean sendMessage(MailMessage data) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("kingyin-mail@qq.com");
            helper.setTo(data.getUsernames());
            helper.setSubject(data.getSubject());
            String body = data.getContext();
            String context = MailHtml.header+body+MailHtml.footer;
            helper.setText(context, true);
            javaMailSender.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean sendMessageHtmlEmpty(MailMessage data) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("kingyin-mail@qq.com");
            helper.setTo(data.getUsernames());
            helper.setSubject(data.getSubject());
            helper.setText(data.getContext(), true);
            javaMailSender.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
